package com.bmf.admin.utils;


import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 豆复制跑龙套
 *
 * @author
 * @date 2022/10/07
 */
public class BeanCopyUtils {
    /**
     * Bean 复制实用程序
     */
    private BeanCopyUtils() {
    }
    /**
     * 复制 Bean
     *
     * @param source 源
     * @param clazz  克拉兹
     * @return {@code V}
     */
    public static <V> V copyBean(Object source,Class<V> clazz) {
        //创建目标对象
        V result = null;
        try {
            result = clazz.getDeclaredConstructor().newInstance();
            //实现属性copy
            BeanUtils.copyProperties(source, result);
        } catch (Exception e) {
           throw new RuntimeException("bean copy error");
        }
        //返回结果
        return result;
    }
    /**
     * 复制 Bean 列表
     *
     * @param list  列表
     * @param clazz 克拉兹
     * @return {@code List<V>}
     */
    public static <O,V> List<V> copyBeanList(List<O> list, Class<V> clazz){
        return list.stream()
                .map(o -> copyBean(o, clazz))
                .collect(Collectors.toList());
    }
    /**
     * @param sources
     * @param target
     * @return {@code List<T>}
     */
    public static <S, T> List<T> copyListByStream(List<S> sources, Supplier<T> target) {
        return sources.stream().map(i -> {
            T t = target.get();
            BeanUtils.copyProperties(i, t);
            return t;
        }).collect(Collectors.toList());
    }
    /**
     * 复制 Bean
     *
     * @param sources
     * @param target  目标
     * @return {@code T}
     */
    public static <S, T> T copyBean(S sources, Supplier<T> target) {
            T t = target.get();
            BeanUtils.copyProperties(sources, t);
            return t;
    }
}
